package com.moment.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;




@WebFilter("/AuthenticationFilter")
public class AuthenticationFilter implements Filter {

	private ServletContext context;

	public void init(FilterConfig fConfig) throws ServletException {
		this.context = fConfig.getServletContext();
		this.context.log("AuthenticationFilter initialized");
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;

		String uri = req.getRequestURI();
		this.context.log("Requested Resource::" + uri);

		HttpSession session = req.getSession(false);

		if (session == null
				&& !(uri.endsWith("jsp") || uri.endsWith("html") )) {
			this.context.log("Unauthorized access request");
			res.sendRedirect("/MMP/jsp/index.jsp");
		}
		else {
			// pass the request along the filter chain
			chain.doFilter(request, response);
		}

	}

	/*
	 * boolean authorized = false; if (request instanceof HttpServletRequest) {
	 * HttpSession session = ((HttpServletRequest)request).getSession(false); if
	 * (session != null) { System.out.println("inside 1"); User user = (User)
	 * session.getAttribute("user"); if (user != null) authorized = true;
	 * 
	 * } (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#destroy()
	 */

	public void destroy() {
		// close any resources here
	}

}
